package com.huan.study.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * redis 生产唯一id
 * <a href="https://www.cnblogs.com/xw-01/p/18284716">https://www.cnblogs.com/xw-01/p/18284716</a>
 *
 * @author huan.fu
 * @date 2024/8/12 - 12:22
 */
@Component
public class IdGenerator {
    /**
     * 开始时间戳(单位：秒) 2000-01-01 00:00:00
     */
    private static final long START_TIMESTAMP = 946656000L;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取 ID   格式：时间戳+序列号
     *
     * @param keyPrefix Redis 序列号前缀
     * @return 生成的 ID
     */
    public long getNextId(String keyPrefix) {
        // 获取当前时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 获取 ID 时间戳
        long timestamp = nowSecond - START_TIMESTAMP;
        // 获取当前日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 生成 key
        String key = "incr:" + keyPrefix + ":" + date;
        // 获取序列号
        long count = redisTemplate.opsForValue().increment(key);
        // 生成 ID 并返回
        return timestamp << 32 | count;
    }
}
